<?php

namespace App\Models;

use Encore\Admin\Traits\DefaultDatetimeFormat;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable,DefaultDatetimeFormat;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function addresses(){
        return $this->hasMany(UserAddress::class,"user_id","id");
    }

    //belongsToMany定义一个多对多的关联，第一个参数是关联的模型类名
    //第二个参数是中间表的表名
    //withTimestamps()代表中间表带有的时间戳字段

    public function favoriteProducts(){
        return $this->belongsToMany(Product::class,"user_favorite_products")
        ->withTimestamps()->orderBy("user_favorite_products.created_at","desc");
        //orderby里的值是按中间表创建时间倒序排序
    }

    public function cartItems(){
        return  $this->hasMany(CartItem::class);
    }
}
